package net.uman.framework.modules.web.struts2;

import java.io.IOException;
import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.StaticParametersInterceptor;

public class ExceptionMappingInterceptor extends StaticParametersInterceptor {
	protected Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		try {
			return invocation.invoke();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			
			String msg = getMessage(e);
			invocation.getStack().set("exceptionMessage", msg);
			
			// return Action.ERROR;
			throw e;
		}
	}

	private String getMessage(Throwable e) {
		if (e instanceof DataAccessException) {
			return "数据库操作失败！";
		} else if (e instanceof NullPointerException) {
			return "调用了未经初始化的对象或者是不存在的对象！";
		} else if (e instanceof IOException) {
			return "读写异常！";
		} else if (e instanceof ClassNotFoundException) {
			return "指定的类不存在！";
		} else if (e instanceof ArithmeticException) {
			return "数学运算异常！";
		} else if (e instanceof ArrayIndexOutOfBoundsException) {
			return "数组下标越界!";
		} else if (e instanceof IllegalArgumentException) {
			return "方法的参数错误！";
		} else if (e instanceof ClassCastException) {
			return "类型强制转换错误！";
		} else if (e instanceof SecurityException) {
			return "违背安全原则异常！";
		} else if (e instanceof SQLException) {
			return "操作数据库异常！";
		} else if (e instanceof NoSuchMethodError) {
			return "方法末找到异常！";
		} else if (e instanceof InternalError) {
			return "发生了内部错误";
		} else if (e instanceof Exception) {
			return "程序内部错误，操作失败！";
		}
		return e.toString();
	}
}